package com.example.markingsystem.controller;

import com.example.markingsystem.bean.user;
import com.example.markingsystem.mapper.LoginMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Controller
public class WechatloginTest {

    @Resource
    LoginMapper loginMapper;

    private static final String APP_ID = "wxe55cc3e4ab75907b";

    @RequestMapping("/wechat/totologin")
    public String gettest(){
        return "testtologin";
    }

    @RequestMapping("/wechat/tologin")
    public String toLoginRedirectPage() {
        // 构建微信OAuth2.0授权链接
        String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID +
                "&redirect_uri=http%3A%2F%2F106.14.141.173%3A8800%2Fwechat%2Fgetopenid&response_type=code" +
                "&scope=snsapi_base&state=12345#wechat_redirect";


        //System.out.println("已经传输"+redirectUrl);
        // 返回重定向到授权链接
        return "redirect:" + redirectUrl;
    }

    //备一份可用代码在这里 不要动
    /*
    @GetMapping("/wechat/getopenid")
    public ResponseEntity<String> getOpenId(@RequestParam("code") String code) {


        System.out.println("我的code到底来不来了？"+code);
        // 使用RestTemplate或其他HTTP客户端与微信服务器交换code以获取openid
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        // 拼接请求参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("appid", APP_ID);
        params.add("secret", "e2d604d4b38facd8489311b24b86af93");
        params.add("code", code);
        params.add("grant_type", "authorization_code");

        // 发送请求获取access_token和openid
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(
                "https://api.weixin.qq.com/sns/oauth2/access_token",
                request,
                String.class
        );
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> resultMap = objectMapper.readValue(response.getBody(), Map.class);
            String openid = (String) resultMap.get("openid");
            // 这里可以进一步处理openid并返回相应信息或重定向至登录成功页面
            System.out.println("我的openid是"+openid);

            // 示例：返回openid
            return new ResponseEntity<>(openid, HttpStatus.OK);

        } catch (JsonProcessingException e) {
            // 处理异常
            return new ResponseEntity<>("Failed to retrieve openid", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }*/

    @GetMapping("/wechat/getopenid")
    public String getOpenId(@RequestParam("code") String code, HttpSession session, Model model) {


        //System.out.println("我的code是"+code);
        // 使用RestTemplate或其他HTTP客户端与微信服务器交换code以获取openid
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        // 拼接请求参数
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("appid", APP_ID);
        params.add("secret", "e2d604d4b38facd8489311b24b86af93");
        params.add("code", code);
        params.add("grant_type", "authorization_code");

        // 发送请求获取access_token和openid
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(
                "https://api.weixin.qq.com/sns/oauth2/access_token",
                request,
                String.class
        );
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> resultMap = objectMapper.readValue(response.getBody(), Map.class);
            String openid = (String) resultMap.get("openid");
            // 这里可以进一步处理openid并返回相应信息或重定向至登录成功页面
            System.out.println("我的openid是"+openid);

            //此处添加代码 登录后 获取openid 然后一个service 判断是否有 有则登录 无则进入登录界面并填写内容
            Boolean loginexit = loginMapper.existsbyopenid(openid);

            System.out.println("存在账号吗？"+loginexit);

            if(loginexit){
                String logingetidcode = loginMapper.getidcodeByopenid(openid);
                user nowuser = loginMapper.codegetalluse(logingetidcode);

                //判断次数是否够用，如果够用则-1，否则返回
                if(nowuser.getNumberuse()>=1){
                    //次数-1
                    int fewer = loginMapper.numberuse111(logingetidcode);
                }
                else{
                    //报告没有次数的结果
                    model.addAttribute("reinfo","你的使用次数不够！");
                    return "index";
                }

                //登录成功且有效时，储存
                session.setAttribute("userlogin",logingetidcode);
                session.setAttribute("nowopenid",openid);
                System.out.println("已经储存"+openid);

                //判断这个idcode是否为管理员
                if(nowuser.getIidentity()==1){
                    //跳转管理员登录界面
                    return "test";
                }

                //这之后需要判断是否已经填过了信息，填完了直接进入主页
                //联合查询三个信息表内是否含有其身份信息，有就直接跳转主页
                Boolean completely = loginMapper.checkidcode(logingetidcode);
                if(completely){
                    //直接跳转主页
                    return "test";
                }

                String aaa = nowuser.getIdcode();
                //判断这个idcode属于管理员外的哪一个身份
                char thirdDigit = aaa.charAt(aaa.length() - 3);
                int digit = Character.getNumericValue(thirdDigit);

                if(digit==1){
                    return "benxiaolaoshiInfo";
                }
                if(digit==5){
                    return "yanjiushengInfo";
                }
                if(digit==8){
                    //return "waixiaolaoshiInfo";
                    return "teacherInfo";
                }

            }

            //没有绑定过账号的状态
            else {
                session.setAttribute("nowopenid",openid);
                System.out.println("已经储存"+openid);
                return "index";
            }

        } catch (JsonProcessingException e) {
            // 处理异常
            return "error";
        }
        //这里也肯定走不到...
        return "error";
    }


}
